<?php

namespace Modules\Asset\Entities;

use Illuminate\Database\Eloquent\Builder;
use \Modules\Order\Entities\BaseOrder;

use ThrowException;
use Setting;

use Asset;

// 发货订单
class AssetOrder extends BaseOrder
{
    protected $guarded = [];
    protected $table = 'orders';

    static public $resourceName = '虚拟资产订单';
    static public $orderType = 'asset';

    public $isAutoComplete = true;

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('assetOrder', function(Builder $builder) {
            $builder->type('asset');
        });
    }

    public function generateNumber()
    {
        $number = 'V' . date('ymdHis') . $this->user_id . '0' . rand(10000, 99999);
        return $number;
    }

    // 创建后回调
    public function createdListenerSync()
    {
        // foreach ($this->skus as $orderSku) {
        //     $packageSku = $orderSku->base_sku;

        //     // 提交发货完成
        //     $packageSku->pick($this);
        // }
    }

    // 支付成功回调
    public function paidListenerSync()
    {
        $orderSkus = $this->skus;
        $user = $this->user;

        // 虚拟资产发放给用户
        foreach ($orderSkus as $orderSku) {
            if ($orderSku->sku_assets) {
                Asset::sendTo($orderSku->sku_assets, $user, [
                    'description' => '订单发放',
                    'order' => $this,
                    'sub_type' => 4     // 4为订单充值
                ]);
            }
        }

        return true;

        // $this->ticket->pay_status = 1;
        // $this->ticket->save();

        // $this->autoFreight();
        // \Log::error('package order pay: ' . $this->id);
    }
}
